#!/bin/bash

SpringBoot=$2

if [ "$1" = "" ];
then
    echo -e "please use  {start|stop|restart|status}."
    exit 1
fi

if [ "$SpringBoot" = "" ];
then
    echo -e "please input springboot name."
  
  exit 1
fi
usage() {
    echo "Usage: [start|stop|restart|status] [SpringBoot]."
    exit 1
}

function is_exist() { 
   # 获取PID
   pid=$(ps -ef |grep java|grep giscloud-generator|grep -v grep|awk '{print $2}')
   # -z "${pid}"判断pid是否存在，如果不存在返回1，存在返回0
   if [ -z "${pid}" ]; then
    # 如果进程不存在返回1
      return 1
   else
    # 进程存在返回0
      return 0
   fi
}

function start()
{
    is_exist
    if [ $? -eq "0" ]; then
        echo "$SpringBoot is already running,pid=${pid}."
    else
        echo "Start $SpringBoot ..."
      nohup java -server -XX:+UseG1GC -Xmx1200m -Xms1200m -XX:MaxMetaspaceSize=200M -XX:MetaspaceSize=200M -Xss256K -XX:+DisableExplicitGC -XX:MaxGCPauseMillis=200\
       -XX:InitiatingHeapOccupancyPercent=45 -XX:NewRatio=1 -XX:MaxGCPauseMillis=200 -XX:InitiatingHeapOccupancyPercent=45 -XX:NewRatio=1 -XX:SurvivorRatio=6\
       -XX:SoftRefLRUPolicyMSPerMB=0 -XX:G1ReservePercent=10 -XX:G1HeapRegionSize=32m -XX:ConcGCThreads=2 -XX:LargePageSizeInBytes=128M -XX:+UseFastAccessorMethods\
       -Dloader.path=/opt/app/lib -jar $SpringBoot --spring.config.location=/opt/app/application.properties  > /dev/null 2>&1 &
        pid=$(echo $!)
      echo "$SpringBoot start success, pid=$!."
    fi
}

function stop()
{
   echo "Stop $SpringBoot"
   is_exist
   if [ $? -eq "0" ]; then
     kill -9 ${pid}
     echo "${SpringBoot} process stop, pid=${pid}."
   else
     echo "$SpringBoot is not running!"
   fi
}

function restart()
{
    stop
    sleep 2
    start
}

function status()
{
   is_exist
   if [ $? -eq "0" ]; then
     echo "$SpringBoot is running, pid is ${pid}."
   else
     echo "$SpringBoot is not running."
   fi
}

case $1 in
    "start")
     start
     ;;
   "stop")
     stop
     ;;
   "status")
     status
     ;;
   "restart")
     restart
     ;;
   *)
     usage
     ;;
esac
exit 0
